package com.dd.cloud.user.service.paynotice.promode.notice;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dd.cloud.common.constants.ConsultConstants;
import com.dd.cloud.user.entity.consult.ConsultSubscribe;
import com.dd.cloud.user.entity.order.OrderPay;
import com.dd.cloud.user.service.consule.IConsultSubscribeService;
import com.dd.cloud.user.service.doctor.IDoctorOrderIncomeDetailService;
import com.dd.cloud.user.service.log.ILogErrorService;
import com.dd.cloud.user.service.paynotice.promode.NoticeService;
import com.dd.cloud.user.service.paynotice.promode.NoticeType;
import com.dd.cloud.user.service.plat.TemplateMessAgeService;
import com.zk.pay.constants.CS;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * 退款预约产品回调
 */
@Slf4j
@NoticeType(source = CS.NOTICE_SOURCE.REFUND, proType = CS.NOTICE_CHANNEL.SINGLE)
public class ConsultRefundNoticeService implements NoticeService {
    @Autowired
    private IConsultSubscribeService consultSubscribeService;
    @Autowired
    private ILogErrorService logErrorService;
    @Autowired
    private IDoctorOrderIncomeDetailService doctorOrderIncomeDetailService;
    @Autowired
    private TemplateMessAgeService templateMessAgeService;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 退款处理逻辑
     *
     * @param request
     * @param orderPay 订单对象
     * @param flowNo   流水编号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Async
    public void notice(HttpServletRequest request, OrderPay orderPay, String flowNo) {
        try {
            String serverNo = orderPay.getServerNo();
            UpdateWrapper<ConsultSubscribe> uw = new UpdateWrapper<>();
            uw.lambda().eq(ConsultSubscribe::getId, Integer.valueOf(serverNo))
                    .set(ConsultSubscribe::getStatus, ConsultConstants.Status.REFUND);
            boolean update = consultSubscribeService.update(uw);
            log.info("问诊id为{},问诊订单退款成功!!", Integer.valueOf(serverNo));
            log.info("~~进入分账退款~~");
            doctorOrderIncomeDetailService.addConsultOrderIncomeDetail(orderPay);
            log.info("发送退款模板消息,发送预约取消模板");
            templateMessAgeService.sendRabbitConsultRefundOrder(orderPay.getOrderNo());
            //退款埋点
            String wzOrderNo = "wz" + orderPay.getOrderNo();
            redisTemplate.opsForValue().set(wzOrderNo, "1", 60L, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
            logErrorService.presBackLog("预约回调退款抛异常", "预约退款回调异常", "serverNo=" + orderPay.getServerNo());
        }
    }
}
